<template>
  <div class="customer-home">
    <!-- 轮播图 -->
    <el-carousel height="400px" class="banner">
      <el-carousel-item v-for="item in banners" :key="item.id">
        <div class="banner-item" :style="{ background: item.color }">
          <h2>{{ item.title }}</h2>
          <p>{{ item.desc }}</p>
        </div>
      </el-carousel-item>
    </el-carousel>
    
    <!-- 分类导航 -->
    <div class="categories">
      <h3 class="section-title">🏪 商品分类</h3>
      <div class="category-grid">
        <div
          v-for="category in categories"
          :key="category.id"
          class="category-item"
          @click="goToProducts(category.id)"
        >
          <div class="category-icon">{{ category.icon || '📦' }}</div>
          <span class="category-name">{{ category.name }}</span>
          <span class="product-count">{{ category.productCount || 0 }}件商品</span>
        </div>
      </div>
    </div>
    
    <!-- 热销商品 -->
    <div class="hot-products">
      <h3 class="section-title">热销商品</h3>
      <div class="product-grid">
        <div
          v-for="product in hotProducts"
          :key="product.id"
          class="product-card"
          @click="goToDetail(product.id)"
        >
          <div class="product-image">
            <img :src="getImageUrl(product.image)" :alt="product.name" />
          </div>
          <div class="product-info">
            <h4>{{ product.name }}</h4>
            <p class="product-desc">{{ product.description }}</p>
            <div class="product-footer">
              <span class="price">¥{{ product.price }}</span>
              <el-button
                type="primary"
                size="small"
                :icon="ShoppingCart"
                @click.stop="addToCart(product)"
              >
                加入购物车
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { getHotProducts } from '@/api/product'
import { getCategoryList } from '@/api/category'
import { ElMessage } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'

const router = useRouter()
const cartStore = useCartStore()

const banners = ref([
  { id: 1, title: '欢迎来到便利店商城', desc: '新鲜商品，优质服务', color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' },
  { id: 2, title: '限时优惠', desc: '全场8折起', color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)' },
  { id: 3, title: '新品上架', desc: '每日新鲜直达', color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)' }
])

const categories = ref([])

const hotProducts = ref([])

onMounted(async () => {
  // 加载分类列表（如果需要动态加载）
  loadCategories()
  
  // 加载热销商品
  try {
    const res = await getHotProducts(8)
    if (res.code === 200 && res.data) {
      hotProducts.value = res.data
    }
  } catch (error) {
    console.error('加载热销商品失败:', error)
    // 使用模拟数据
    hotProducts.value = [
      { id: 1, name: '可口可乐', description: '经典口味 330ml', price: 3.5, image: 'https://via.placeholder.com/200', stock: 100 },
      { id: 2, name: '薯片', description: '原味 100g', price: 6.0, image: 'https://via.placeholder.com/200', stock: 50 },
      { id: 3, name: '矿泉水', description: '纯净水 550ml', price: 2.0, image: 'https://via.placeholder.com/200', stock: 200 },
      { id: 4, name: '方便面', description: '红烧牛肉味', price: 4.5, image: 'https://via.placeholder.com/200', stock: 80 },
      { id: 5, name: '巧克力', description: '丝滑醇厚 50g', price: 8.0, image: 'https://via.placeholder.com/200', stock: 60 },
      { id: 6, name: '牛奶', description: '纯牛奶 250ml', price: 5.5, image: 'https://via.placeholder.com/200', stock: 100 },
      { id: 7, name: '饼干', description: '曲奇饼干 200g', price: 12.0, image: 'https://via.placeholder.com/200', stock: 40 },
      { id: 8, name: '口香糖', description: '清新口气', price: 3.0, image: 'https://via.placeholder.com/200', stock: 150 }
    ]
  }
})

const loadCategories = async () => {
  try {
    const res = await getCategoryList()
    if (res.code === 200 && res.data) {
      // 只显示启用状态的分类，最多显示8个
      categories.value = res.data
        .filter(cat => cat.status === 1)
        .slice(0, 8)
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

const goToProducts = (categoryId) => {
  router.push({ path: '/customer/products', query: { categoryId } })
}

const goToDetail = (id) => {
  router.push(`/customer/products/${id}`)
}

const addToCart = async (product) => {
  // 传递productId和数量，cartStore.addItem会显示提示信息
  await cartStore.addItem(product.id, 1)
}

// 获取图片URL（处理相对路径和绝对路径）
const getImageUrl = (url) => {
  if (!url) return 'https://via.placeholder.com/200'
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  // 通过API代理访问图片
  return 'http://localhost:8080' + url
}
</script>

<style lang="scss" scoped>
.customer-home {
  .banner {
    margin-bottom: 30px;
    border-radius: 8px;
    overflow: hidden;
    
    .banner-item {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: white;
      
      h2 {
        font-size: 36px;
        margin-bottom: 10px;
      }
      
      p {
        font-size: 18px;
      }
    }
  }
  
  .section-title {
    font-size: 24px;
    margin-bottom: 20px;
    padding-left: 10px;
    border-left: 4px solid #409eff;
  }
  
  .categories {
    margin-bottom: 40px;
    
    .category-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 20px;
      
      .category-item {
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        padding: 25px 15px;
        border-radius: 12px;
        border: 2px solid #f0f0f0;
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 20px rgba(64, 158, 255, 0.2);
          border-color: #409eff;
          
          .category-icon {
            transform: scale(1.2);
          }
        }
        
        .category-icon {
          font-size: 48px;
          transition: transform 0.3s;
          margin-bottom: 5px;
        }
        
        .category-name {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }
        
        .product-count {
          font-size: 12px;
          color: #909399;
        }
      }
    }
  }
  
  .hot-products {
    .product-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
      gap: 20px;
      
      .product-card {
        background: white;
        border-radius: 8px;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.3s;
        
        &:hover {
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          
          .product-image img {
            transform: scale(1.05);
          }
        }
        
        .product-image {
          height: 200px;
          overflow: hidden;
          background: #f5f5f5;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s;
          }
        }
        
        .product-info {
          padding: 15px;
          
          h4 {
            font-size: 16px;
            margin-bottom: 8px;
          }
          
          .product-desc {
            font-size: 12px;
            color: #999;
            margin-bottom: 12px;
          }
          
          .product-footer {
            display: flex;
            align-items: center;
            justify-content: space-between;
            
            .price {
              font-size: 20px;
              color: #ff4d4f;
              font-weight: bold;
            }
          }
        }
      }
    }
  }
}
</style>











